import {withLayout} from '@/layout/Layout';
import {GetStaticPaths, GetStaticProps, GetStaticPropsContext} from 'next';
import axios from 'axios'
import {MenuItem} from '@/interfaces/menu.interface';
import {ProductModel} from "@/interfaces/product.interface";
import {TopLevelCategory, TopPageModel} from "@/interfaces/page.interface";
import {ParsedUrlQuery} from "querystring";
import {firstLevelMenu} from "@/helpers/helpers";

const firstCategory = 0;
function TopPage({menu, page, products}: TopPageProps): JSX.Element {
    return (
        <>
        </>
    );
}

export default withLayout(TopPage);
export const getStaticPaths: GetStaticPaths = async () => {
    let paths:string[] = [];
    for (const m of firstLevelMenu) {
        const {data: menu} = await axios.post<MenuItem[]>(process.env.NEXT_PUBLIC_DOMAIN + '/api/top-page/find', {
            firstCategory:m.id
        })
        paths = paths.concat(menu.flatMap((s) => s.pages.map(p => `/${m.route}/${p.alias}`)))
    }

    return {
        paths,
        fallback: true
    }
}

export const getStaticProps: ({params}: GetStaticPropsContext<ParsedUrlQuery>) => Promise<{ notFound: boolean } | {
    props: { firstCategory: number; menu: MenuItem[] }
}> = async ({ params }: GetStaticPropsContext<ParsedUrlQuery>) => {
    if (!params) {
        return {
            notFound: true
        }
    }
    const firstCategoryItem = firstLevelMenu.find( m => m.route == params.type)
    if (!firstCategoryItem) {
        return {
            notFound: true
        }
    }
    try {
        const {data: menu} = await axios.post<MenuItem[]>(process.env.NEXT_PUBLIC_DOMAIN + '/api/top-page/find', {
            firstCategory: firstCategoryItem.id
        })
        if (menu.length == 0) {
            return {
                notFound: true
            }
        }
        const {data: page} = await axios.get<TopPageModel>(process.env.NEXT_PUBLIC_DOMAIN + '/api/top-page/byAlias/' + params.alias)
        const {data: products} = await axios.post<ProductModel[]>(process.env.NEXT_PUBLIC_DOMAIN + '/api/product/find/', {
            category: page.category,
            limit: 1
        })
        return {
            props: {
                menu,
                firstCategory: firstCategoryItem.id
            }
        }
    }catch (e) {
        return {
            notFound: true
        }
    }
}

interface TopPageProps extends Record<string, unknown> {
    menu: MenuItem[];
    products: ProductModel[];
    page: TopPageModel;
    firstCategory: TopLevelCategory
}
